<?php

/**
 * Yii Controller CrudController
 *
 * @author nguyenmanhluu v1.0
 * @since Aug 8, 2013 - 6:47:20 PM
 * @author trongkhoi v1.1
 */
class CrudController extends MyController
{

    public $modelName = '';
    public $model = '';
    public $title = '';
    public $indexColumns = array();
    public $formColumns = array();
    public $indexView = '/_crud/index';
    public $formView = '/_crud/_form';
    public $currentLimit = 20;
    public $ajaxControl = TRUE;
    public $allowCreate = TRUE;

    public function init()
    {
        parent::init();
        
        if (isset($_GET['pageSize'])) {
            Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);
            unset($_GET['pageSize']);
        }
        // Thiết lập model dùng chung 
        $this->_setModel();
    }

    protected function _setModel()
    {
        // Tạo model được sử dụng chính trong Controller này
        $id = isset($_GET['id']) ? $_GET['id'] : FALSE;

        $model = $this->modelName;

        if ($model && class_exists($model))
        {
            if ($id)
            {
                $this->model = call_user_func($model . '::model');
                $this->model = $this->model->findByPk($id);
                if ($this->model == NULL)
                    throw new CHttpException(400, Yii::t('yii', 'Your request is invalid.'));
            }
            else
                $this->model = new $model;
        }
    }

    public function actionIndex()
    {
        $this->checkAccess();
        $model = new $this->modelName('search');
        if (isset($_GET[$this->modelName]))
            $model->attributes = $_GET[$this->modelName];
        $this->render($this->indexView, array(
            'model' => $model,
        ));
    }

    public function actionSearch()
    {
        $this->checkAccess();

        $this->pageTitle = Yii::t('main', 'Search');
        $this->actionIndex();
    }

    public function actionView($id)
    {
        $this->checkAccess();

        $this->pageTitle = Yii::t('main', 'View');
        echo $id;
    }

    public function actionCreate()
    {
        $this->checkAccess();

        $controller = Yii::app()->controller->id;
        $this->pageTitle = Yii::t('user', ucfirst($controller));
        $this->pageTitle .= " / " . Yii::t('user', 'Create');

        $this->model->setScenario('create');
        $this->form('Create');
//
//        if (Yii::app()->request->isAjaxRequest)
//        {
//            $cs = Yii::app()->clientScript;
//            $cs->scriptMap = array(
//                'jquery.js' => false,
//                'jquery.yiiactiveform.js' => false,
//            );
//            $this->layout = '//layouts/ajax';
//        }
        $this->render($this->formView, array('model' => $this->model));
    }

    public function actionEdit()
    {
        $this->checkAccess();

        $controller = Yii::app()->controller->id;
        $this->pageTitle = Yii::t('user', ucfirst($controller));
        $this->pageTitle .= " / " . Yii::t('user', 'Edit');

        $this->model->setScenario('edit');
        $this->form('Edit');
//
//        if (Yii::app()->request->isAjaxRequest)
//        {
//            $cs = Yii::app()->clientScript;
//            $cs->scriptMap = array(
//                'jquery.js' => false,
//                'jquery.yiiactiveform.js' => false,
//            );
//            $this->layout = '//layouts/ajax';
//        }
        $this->render($this->formView, array('model' => $this->model));
    }

    public function actionDelete($id)
    {
        $this->checkAccess();
        $model = call_user_func($this->modelName . '::model');
        try
        {
            $model->deleteByPk($id);
            if (!isset($_GET['ajax']))
                Yii::app()->user->setFlash('success', Yii::t('main', 'Deleted Successfully'));
        }
        catch (CDbException $e)
        {
            if (!isset($_GET['ajax']))
                Yii::app()->user->setFlash('error', Yii::t('main', 'Deleted Unsuccessfully'));
        }

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array($this->indexView));
    }

    protected function form($action = 'Create')
    {
        // if it is ajax validation request
        if (isset($_POST['ajax']))
        {
            echo CActiveForm::validate($this->model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST[$this->modelName]))
        {
            $this->model->attributes = $_POST[$this->modelName];
            // validate user input and redirect to the previous page if valid
            if ($this->model->validate())
            {
                if (!$this->save($action))
                {
                    $noti = Yii::t('form', 'Can\'t do {action} , please try again!', array(
                            '{action}' => Yii::t('form', $action)
                    ));
                    Yii::app()->user->setFlash('success', $noti);
                }
                else
                {
                    $noti = Yii::t('form', '{action} successful!', array(
                            '{action}' => Yii::t('form', $action)
                    ));
                    Yii::app()->user->setFlash('success', $noti);

                    $submit = isset($_POST['submit']) ? $_POST['submit'] : 'submit';
                    if ($submit == 'submit')
                    {
                        $getParams = $_GET;
                        // Nếu trường hợp update thì khi ra ngoài list sẽ bỏ id đi
                        if (isset($getParams['id']))
                        {
                            unset($getParams['id']);
                        }
                        $this->redirect($this->createUrl(Yii::app()->controller->id . "/index", $getParams));
                    }
                    elseif ($submit == 'continue')
                    {
                        $this->refresh();
                    }
                }
            }
            else
            {
//                echo CActiveForm::validate($this->model);
            }
        }
    }

    protected function save($action = 'Create')
    {
        return $this->model->save();
    }

    public function actionDeleteList()
    {
        $this->checkAccess();
        if ($_POST['ids'])
        {
            $ids = implode(',', $_POST['ids']);
            $model = call_user_func($this->modelName . '::model');
            try
            {
                $model->deleteAll("id in ($ids)");
                if (!isset($_GET['ajax']))
                    Yii::app()->user->setFlash('success', Yii::t('main', 'Deleted Successfully'));
            }
            catch (CDbException $e)
            {
                if (!isset($_GET['ajax']))
                    Yii::app()->user->setFlash('error', Yii::t('main', 'Deleted Unsuccessfully'));
            }
//            Yii::app()->db->createCommand()->delete(lcfirst($this->modelName), 'id in (' . $ids . ')');
        }
    }

}

/** 
 * End file CrudController
 */
